package com.example.weight.wormHandle.garbageDisposal.researchDevelopment;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.arrayAdapter.MyAdapter;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.flocculation.xuningguzhang;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class OutcomingSceneInsectSeparate extends AppCompatActivity implements View.OnClickListener{

    private String name, factory;
    private String device_name;
    private  int belongTo_id = -1;
    private TextView outcoming_scene_separateDate;

    private TextView insectSeparate_start;
    private TextView insectSeparate_end;

    private Button btn_insectSeparate_start;
    private Button btn_insectSeparate_end;

    private TitleBar titleBar;

    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    //出料日期
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    Date separateDate = new Date(System.currentTimeMillis());
    private List<BatchGroupNumber> batchGroupNumberList;
    private Spinner batchGroupNumber;
    private List<String> device2NameList;
    private Spinner device2Name;

    //    private TextView device2Name;
    //老虫重量
    private TextView insect_weight;
    //杂质重量
    private TextView impurity_weight;
    //虫粪重量
    private TextView insect_dung_weight_2;
    String activeButton = new String();
    private EditText remark;
    private EditText outcoming_scene_separate_person;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.outcoming_scene_insect_separate);

        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                OutcomingSceneInsectSeparate.this.finish();
            }

            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });

        /**
         * 显示设置日期
         */
        outcoming_scene_separateDate = findViewById(R.id.outcoming_scene_separateDate);
        outcoming_scene_separateDate.setText(simpleDateFormat.format(separateDate));
//
        //老虫重量
        insect_weight = findViewById(R.id.outcoming_scene_insect_weight);
        //杂质重量
        impurity_weight = findViewById(R.id.outcoming_scene_impurity_weight);
        //虫粪重量
        insect_dung_weight_2 = findViewById(R.id.outcoming_scene_insect_dung_weight_2);

        insectSeparate_start = (TextView) findViewById(R.id.insectSeparate_start);
        insectSeparate_start.setOnClickListener(this);
        insectSeparate_end = (TextView) findViewById(R.id.insectSeparate_end);
        insectSeparate_end.setOnClickListener(this);


        btn_insectSeparate_start = (Button) findViewById(R.id.btn_insectSeparate_start);
        btn_insectSeparate_end = (Button) findViewById(R.id.btn_insectSeparate_end);
        btn_insectSeparate_start.setOnClickListener(this);
        btn_insectSeparate_end.setOnClickListener(this);
        batchGroupNumberList = new ArrayList<>();
        batchGroupNumber = findViewById(R.id.batch_group_number_list);
        device2NameList = new ArrayList<>();
        device2Name = findViewById(R.id.outcoming_scene_device_2_name);
        remark = findViewById(R.id.outcoming_scene_remark);
        outcoming_scene_separate_person = findViewById(R.id.outcoming_scene_separate_person);
        outcoming_scene_separate_person.setText(name);

        device2Name.setEnabled(false);

        //获取待分离设备列表
        RequestQueue queue = Volley.newRequestQueue(this);
        String url2 = Config.url + "/research/separate/getList" + "?factory=" + factory;
        StringRequest stringRequest2 = new StringRequest(Request.Method.GET, url2,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if( data.length()>0){
                                    for (int i=0; i < data.length(); i++){
                                        JSONObject record = data.getJSONObject(i);
                                        batchGroupNumberList.add(new BatchGroupNumber(record.getInt("id"),record.getString("batch"),record.getString("zubie"),record.getString("boxNumber"),"",""));
                                        device2NameList.add(new String(record.getString("deviceName1")));
                                    }
                                    Log.d("batchGroupNumberList", batchGroupNumberList.toString());

                                    ArrayAdapter<BatchGroupNumber> adapter = new ArrayAdapter<BatchGroupNumber>(OutcomingSceneInsectSeparate.this, android.R.layout.simple_spinner_item,batchGroupNumberList);
                                    batchGroupNumber.setAdapter(adapter);
                                    batchGroupNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            belongTo_id = batchGroupNumberList.get(position).id;
                                            device2Name.setSelection(position);
                                        }
                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {
                                            belongTo_id = -1;
                                        }
                                    });
                                    batchGroupNumber.setSelection(0,true);

                                    ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(OutcomingSceneInsectSeparate.this, android.R.layout.simple_spinner_item,device2NameList);
                                    device2Name.setAdapter(adapter1);
                                    device2Name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            device_name = device2NameList.get(position);
                                        }
                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {
                                            device_name = "";
                                        }
                                    });
                                    device2Name.setSelection(0,true);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(OutcomingSceneInsectSeparate.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest2.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest2);

//        //获取设备名称
//        String url = Config.url + "/research/crush/getlast" + "?factory=" + factory;
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//                            if (!jsonObject.isNull("data")) {
//                                JSONObject data = jsonObject.getJSONObject("data");
//                                device2NameList.add(new String(data.getString("deviceName1")));
////                                JSONArray data = jsonObject.getJSONArray("data");
////                                if( data.length()>0){
////                                    for (int i=0; i < data.length(); i++){
////                                        JSONObject record = data.getJSONObject(i);
////                                        device2NameList.add(new String("书柜" + record.getString("deviceName1")));
////                                    }
////                                    Log.d("deviceNameList", device2NameList.toString());
////
//                                    ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(OutcomingSceneInsectSeparate.this, android.R.layout.simple_spinner_item,device2NameList);
//                                    device2Name.setAdapter(adapter1);
//                                    device2Name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                                        @Override
//                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                                            device_name = device2NameList.get(position);
//                                        }
//                                        @Override
//                                        public void onNothingSelected(AdapterView<?> parent) {
//                                            device_name = "";
//                                        }
//                                    });
//                                    device2Name.setSelection(0,true);
////                                }
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(OutcomingSceneInsectSeparate.this,
//                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        });
//        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        queue.add(stringRequest);

    }

    public void save(View view) {
        if (belongTo_id == -1){
            Toast.makeText(this, "请先选择批次组别和编号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (device_name.equals("")) {
            Toast.makeText(this, "请填写设备名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if (insectSeparate_start.getText().toString().equals("")) {
            Toast.makeText(this, "请填写老虫分离开始时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (insectSeparate_end.getText().toString().equals("")) {
            Toast.makeText(this, "请填写老虫分离结束时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (insect_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写老虫重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (impurity_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写杂质重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (insect_dung_weight_2.getText().toString().equals("")) {
            Toast.makeText(this, "请填写虫粪重量", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {

                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/research/separate/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(OutcomingSceneInsectSeparate.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(OutcomingSceneInsectSeparate.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(OutcomingSceneInsectSeparate.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("jy", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", belongTo_id+"");
                            map.put("seperateDate", simpleDateFormat.format(separateDate));
                            map.put("insectSeparateStarttime", insectSeparate_start.getText().toString());
                            map.put("insectSeparateEndtime", insectSeparate_end.getText().toString());
                            map.put("device2Name", "书柜"+device_name);
                            map.put("insectWeight", insect_weight.getText().toString());
                            map.put("impurityWeight", impurity_weight.getText().toString());
                            map.put("insectDungWeight", insect_dung_weight_2.getText().toString());
                            map.put("remark", remark.getText().toString());
                            map.put("separatePerson",outcoming_scene_separate_person.getText().toString());
                            map.put("factory",factory);
                            System.out.println(map.toString());

                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
    /**
     * 时间选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showTimePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        Log.d("jy","showTimePickerDialog");
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog( activity,themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv.setText(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.HOUR_OF_DAY)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }
    @Override
    public void onClick(View view) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        switch (view.getId())  {
            case R.id.btn_insectSeparate_start:
                Date date_3_start = new Date(System.currentTimeMillis());
                String s_3_start = simpleDateFormat.format(date_3_start);
                insectSeparate_start.setText(s_3_start);
                btn_insectSeparate_start.setEnabled(false);
                break;
            case R.id.btn_insectSeparate_end:
                Date date_3_end = new Date(System.currentTimeMillis());
                String s_3_end = simpleDateFormat.format(date_3_end);
                insectSeparate_end.setText(s_3_end);
                btn_insectSeparate_end.setEnabled(false);
                break;
            case R.id.insectSeparate_start:
                showTimePickerDialog(this,  2, insectSeparate_start, calendar);;
                break;
            case R.id.insectSeparate_end:
                showTimePickerDialog(this,  2, insectSeparate_end, calendar);;
                break;
            default:
                break;
        }
    }

    /**
     * 称重接口
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "insect_weight_btn":
                insect_weight.setText(weight);
                break;
            case "impurity_weight_btn":
                impurity_weight.setText(weight);
                break;
            case "insect_dung_weight_btn":
                insect_dung_weight_2.setText(weight);
                break;
            default:
                break;
        }
    }
    public void goWeight(View view) {
        switch (view.getId()) {

            case R.id.insect_weight_btn:
                activeButton = "insect_weight_btn";
                break;
            case R.id.impurity_weight_btn:
                activeButton = "impurity_weight_btn";
                break;
            case R.id.insect_dung_weight_btn:
                activeButton = "insect_dung_weight_btn";
                break;
            default:
                break;
        }
        Intent intent = new Intent(OutcomingSceneInsectSeparate.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }
}
